package org.dk.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.dk.domain.DataResult;
import org.dk.em.DataResultEnum;
import org.dk.exception.LoginException;
import org.dk.pojo.TbSeller;
import org.dk.service.SellerService;
import org.dk.util.ShiroUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("sellerController")
public class SellerController {

    @Reference
    private SellerService sellerService;

    @RequestMapping("register")
    @ResponseBody
    public DataResult register(TbSeller tbSeller){
        try {
            String salt = ShiroUtils.generateSalt(10);
            tbSeller.setYan(salt);
            tbSeller.setYancount(3);
            String md5 = ShiroUtils.encryptPassword("MD5", tbSeller.getPassword(), salt, 3);
            tbSeller.setPassword(md5);
            tbSeller.setCreateTime(new Date());
            sellerService.insertSeller(tbSeller);
            return DataResult.buildDataResult(DataResultEnum.SUCCESS);
        }catch (Exception e){
            return DataResult.buildDataResult(DataResultEnum.ERROR);
        }
    }
    @RequestMapping("toShoplogin")
    public String toShoplogin(){
           return "shoplogin";
    }

    @RequestMapping("login")
    @ResponseBody
    public DataResult login (TbSeller tbSeller){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(tbSeller.getSellerId(), tbSeller.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            return DataResult.buildDataResult(DataResultEnum.ERROR).setData("账号或密码错误");
        }catch (LoginException e){
            return DataResult.buildDataResult(DataResultEnum.ERROR).setData(e.getMessage());
        }
        return DataResult.buildDataResult(DataResultEnum.SUCCESS);
    }
}
